﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using PagedList;
using SIG.Service;
using SIG.Model;
using System;

using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.Model.Enums;
using SIG.ViewModel;
using SIG.Infrastructure.Extensions;
using System.Xml.Linq;
using SIG.Infrastructure.Helper;
using SIG.Resources.Admin;
using SIG.Service.Case;
using SIG.ViewModel.Admin.Blogs;
using SIG.Model.Blogs;
using SIG.InputModel.Admin.Blogs;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class PostController : BaseController
    {
        private readonly IPostCategoryService _categoryService;
        private readonly IPostService _postService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public PostController(IPostCategoryService categoryService, IPostService postService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _categoryService = categoryService;
            _postService = postService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;


        }
        #region Posts


        [HttpGet]
        public ActionResult Index(int? page, int? categoryId, string Keyword)
        {

            var postListVM = new PostListVM();

            postListVM.CategoryId = categoryId ?? 0;
            postListVM.PageIndex = (page ?? 1) - 1;
            postListVM.PageSize = SettingsManager.Blog.PageSize;
            postListVM.Keyword = Keyword;

            int count;
            var posts = _postService.GetPagedElements(postListVM.PageIndex, postListVM.PageSize, postListVM.Keyword, postListVM.CategoryId, out count);

            var postDtos = _mapper.Map<IEnumerable<Post>, IEnumerable<PostVM>>(posts.AsEnumerable());

            //   postListVM.Posts = postDtos;
            postListVM.TotalCount = count;

            var categoryList = _categoryService.GetAll().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            postListVM.Posts = new StaticPagedList<PostVM>(postDtos, postListVM.PageIndex + 1, postListVM.PageSize, postListVM.TotalCount);
            //  ViewBag.OnePageOfPosts = postsAsIPagedList;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(postListVM);

        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/BlogSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        public ActionResult Add()
        {
            var post = new PostIM { Active = true };

            var categorys = _categoryService.GetAll().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;
            return View(post);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Add(PostIM post)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {

                var newPost = _mapper.Map<PostIM, Post>(post);
                _postService.Create(newPost);

                if (!string.IsNullOrEmpty(post.Keywords) || !string.IsNullOrEmpty(post.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newPost.Id,
                        Keyword = post.Keywords,
                        Description = post.SEODescription,
                        ModelType = ModelType.ARTICLE
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }

        [HttpGet]
        public ActionResult Edit(int Id)
        {
            var vPost = _postService.GetById(Id);
            if (vPost == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }


            var editPost = _mapper.Map<Post, PostIM>(vPost);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.ARTICLE, editPost.Id);
            if (pageMeta != null)
            {
                editPost.Keywords = pageMeta.Keyword;
                editPost.SEODescription = pageMeta.Description;
            }

            var categorys = _categoryService.GetAll().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;

            return View(editPost);


        }

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public JsonResult Edit(PostIM post)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var editPost = _mapper.Map<PostIM, Post>(post);
                _postService.Update(editPost);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.ARTICLE, editPost.Id);
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(post.Keywords) || !string.IsNullOrEmpty(post.SEODescription))
                {

                    pageMeta.ObjectId = post.Id;
                    pageMeta.Keyword = post.Keywords;
                    pageMeta.Description = post.SEODescription;
                    pageMeta.ModelType = ModelType.ARTICLE;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Active(int id)
        {

            Post vPost = _postService.GetById(id);

            try
            {
                vPost.Active = !vPost.Active;
                _postService.Update(vPost);

                var vm = _mapper.Map<PostVM>(vPost);

                AR.Data = RenderPartialViewToString("_PostItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Recommend(int id)
        {

            Post vPost = _postService.GetById(id);

            try
            {
                vPost.Recommend = !vPost.Recommend;
                _postService.Update(vPost);

                var vm = _mapper.Map<PostVM>(vPost);
                AR.Data = RenderPartialViewToString("_PostItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Post vPost = _postService.GetById(id);

            if (vPost == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _postService.Delete(vPost);

            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Post));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        #endregion


    }
}
